//
//  HHNetworkingManager.swift
//  HHWeibo
//
//  Created by hehuafeng on 2017/2/20.
//  Copyright © 2017年 雷厉峰行. All rights reserved.
//

import UIKit
import AFNetworking

/// 方法请求类型
enum HHHTTPMethod {
    case GET
    case POST
}

class HHNetworkManager: AFHTTPSessionManager {

    /// 网络工具单例
    static let shared: HHNetworkManager = {
        // 1. 实例化对象
        let instance = HHNetworkManager()
        
        // 2. 设置响应反序列化支持的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        // 3. 返回网络请求对象
        return instance
    }()
    
    /// 访问令牌
//    var token: String? //= "2.004v3haD0XJl5ab05602de050xfxpM"
    
    /// 用户账户模型
    lazy var userAccount = HHUserAccount()
    
    /// 登录状态
    var userLogon: Bool {
        return userAccount.access_token != nil
    }
    
    /// 获取用户访问令牌
    ///
    /// - Parameter code: 授权码
    func loadAccessToken(code: String) {
        // 1. 创建urlString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 2. 设置参数字典
        var param = [String : String]()
        param["client_id"] = HHClientID
        param["client_secret"] = HHAppSecret
        param["grant_type"] = "authorization_code"
        param["code"] = code
        param["redirect_uri"] = HHRedirectURI
        
        // 3. 发送网络请求
        request(method: .POST, URLString: urlString, parameters: param) { (json, isSuccess) in
            // 使用YYModel将获取的网络数据设置到用户账户模型中
            // [:] : 表示空字典
            self.userAccount.yy_modelSet(withJSON: json ?? [:])
            
            print(self.userAccount)
        }
    }
    
    /// 封装tokenRequest
    ///
    /// - Parameters:
    ///   - method: 请求方法类型
    ///   - URLString: URLString
    ///   - parameters: 参数字典
    ///   - completion: 完成回调
    func tokenRequest(method: HHHTTPMethod = .GET, URLString: String, parameters: [String : Any]?, completion: @escaping (_ json: Any?, _ isSuccess: Bool) -> ()) {
        // 1. 判断token是否有值
        guard let token = userAccount.access_token else {
            // 1.1 执行回调
            completion(nil, false)
            
            // FIXME: 提示用户登录
            print("没有用户令牌")
            
            // 1.2 返回
            return
        }
        
        // 2. 设置带token的参数字典
        var param: [String : Any]? = parameters
        
        if param == nil {
            param = [String : Any]()
        }
        
        // 3. 设置token
        param?["access_token"] = token
        
        // 4. 发送网络请求
        request(method: method, URLString: URLString, parameters: param!, completion: completion)
    }
    
    
    /// 封装网络请求
    ///
    /// - Parameters:
    ///   - method: 请求方法类型
    ///   - URLString: URLString
    ///   - parameters: 参数字典
    ///   - completion: 完成回调
    func request(method: HHHTTPMethod = .GET, URLString: String, parameters: [String : Any], completion: @escaping (_ json: Any?, _ isSuccess: Bool) -> ()) {
        
        // 1. 定义成功闭包
        let success = { (task: URLSessionDataTask, json: Any?) -> () in
            // 执行回调闭包
            completion(json, true)
        }
        
        // 2. 定义失败闭包
        let failure = { (task: URLSessionDataTask?, error: Error) -> () in
            // 输出错误信息
//            print("网络出错 \(error)")
            
            // 处理token过期
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                // FIXME: token过期, 请再次登录
                print("用户令牌过期")
            }
            
            // 执行回调闭包
            completion(nil, false)
        }
        
        // 3. 发送网络请求
        // 在设置闭包参数时, 闭包中的各项参数一定要一一对应, 
        // 可选的必须对应可选类型, 非可选类型一定要对应非可选类型
        if method == .GET {
            HHNetworkManager.shared.get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else{
            HHNetworkManager.shared.post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
